package com.central.apps.handler.timeTask;

import com.central.app.common.feign.WorkflowClient;
import com.central.app.common.quartz.QuartzJob;
import com.central.app.model.BizFlowApp;
import com.central.app.service.FlowCommonService;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
 *
 * @author 李大超
 * @date 2023/2/15
 */
@Component
@Slf4j
@DisallowConcurrentExecution
public class ConsultTask extends QuartzJob {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private WorkflowClient workflowClient;

    @SneakyThrows
    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) throws JobExecutionException {
        // 查询限时未完成的意见征询配置
        List<Map<String, Object>> list = handlerService.findBySql("select id, app, biz_id, oldExecutors, createUser from biz_flow_consult_cfg t where status = 0 and isTimed = '1' and timeDuration > 0 " +
                " and DATE_FORMAT(createtime,'%Y-%m-%d %H:%i') <= DATE_FORMAT(DATE_SUB(SYSDATE(),INTERVAL t.timeDuration hour) ,'%Y-%m-%d %H:%i')");

        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> map : list) {
                // 删除意见征询配置
                Integer id = MapUtils.getInteger(map, "id");
                String app = MapUtils.getString(map, "app");
                String bizId = MapUtils.getString(map, "biz_id");

                List<Map<String, Object>> dtlList = handlerService.findBySql("select id, consultUserId from biz_flow_consult_dtl where status = '未反馈' and consultId = " + id);

                StringBuilder sb = new StringBuilder();
                if (CollectionUtils.isNotEmpty(dtlList)) {
                    for (Map<String, Object> dtlMap : dtlList) {
                        String consultUserId = MapUtils.getString(dtlMap, "consultUserId");

                        sb.append(consultUserId);
                        sb.append(",");
                    }

                    sb.deleteCharAt(sb.length()-1);
                }

                handlerService.updateBySql("delete from biz_flow_consult_dtl where consultId = " + id);
                handlerService.updateBySql("delete from biz_flow_consult_cfg where id = " + id);

                Map<String, Object> params = new HashMap<>(2);
                params.put("app", app);
                params.put("bizId", bizId);
                BizFlowApp flowApp = flowCommonService.findCurrentTask(params);

                String procInsId = flowApp.getProcInsId();
                String subProcInsId = flowApp.getSubProcInsId();
                procInsId = StringUtils.isNotEmpty(subProcInsId) ? subProcInsId : procInsId;

                // 删除任务执行人
                if (StringUtils.isNotEmpty(sb)) {
                    flowCommonService.delMultiTaskCandidateuser(procInsId, sb.toString());
                    // 更新流程任务认领人
                    handlerService.updateBySql("update act_ru_task set ASSIGNEE_ = null  where PROC_INST_ID_ = '" + procInsId + "'");
                }

                // 还原流程审批人
                String oldExecutors = MapUtils.getString(map, "oldExecutors");
                String createUser = MapUtils.getString(map, "createUser");
                flowCommonService.addMultiTaskCandidateuser(procInsId, oldExecutors);
                workflowClient.claimTask(procInsId, createUser);
            }
        }
    }
}
